package com.lkm.app_ui.ui.sale.p;

import android.os.Handler;
import android.os.Looper;

import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.FunHelp;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.event.OnSubtotalRealEvent;
import com.lkm.app_ui.m.fun.DelegatePayTask;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.m.fun.OnSaleManifestSyncEvent;
import com.lkm.app_ui.m.fun.SaleManifestEntity;
import com.lkm.app_ui.m.vip.VipModule;
import com.lkm.app_ui.ui.fj.FjApp;
import com.lkm.app_ui.ui.sale.SaleContract;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.P;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.Observer;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.ExpandConfig;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m.steelyardserver.event.OnSubtotalEvent;
import com.lkm.market2_0.m.steelyardserver.event.OnWeightInfoChangeEvent;
import com.lkm.mvp.FullLifecycleObserverA;

import java.util.ArrayList;
import java.util.List;

class SubtotalPresenter extends FullLifecycleObserverA implements SaleContract.SubtotalPresenter {
    private Handler   mainHandler;
    private CycleHelp cycleHelp;

    private          SaleContract.SubtotalView       subtotalView;
    private          SaleContract.GoodImagePresenter goodImagePresenter;
    private volatile boolean                         isSubtotalGopay = false;
    private          boolean                         isEditSubtotal;

    private Runnable onGoodImageTackrun;

    public SubtotalPresenter(SaleContract.GoodImagePresenter goodImagePresenter, CycleHelp cycleHelp) {
        this.cycleHelp = cycleHelp;
        mainHandler = new Handler(Looper.getMainLooper());
        this.goodImagePresenter = goodImagePresenter;

    }


    private List<OrderEntity.GoodEntity> souceList = new ArrayList<>();
    private SteelyardDataModule          mSteelyardDataModule;


    private float cur_allTotalPrice = 0;

    private float cur_weightTotalPrice = 0;


    @Override
    public void binView(SaleContract.SubtotalView baseView) {
        if (baseView == null) return;
        if (this.subtotalView == null) {
            this.subtotalView = baseView;
            reOnSubtotalEvent();
            reOnWeightInfoChangeEvent();
        }
        this.subtotalView = baseView;
    }

    @Override
    public void upLastName(String name) {
        if (!souceList.isEmpty())
            souceList.get(souceList.size() - 1).goodName = name;
        //P.d("Bill->upSubtotal->01");
        upSubtotal();
    }


    private void upSubtotal() {
        subtotalView.upSubtotal(souceList);

        float allWeight = 0, allTotalPrice = 0;
        for (OrderEntity.GoodEntity s : souceList) {
            allWeight += s.weight;
            allTotalPrice += s.calPrice();
        }

        SaleManifestEntity saleManifestEntity = new SaleManifestEntity();
        saleManifestEntity.setSouceList(new ArrayList<>(souceList));
        saleManifestEntity.setDiscount("0.00");
        saleManifestEntity.setDiscountAmount("0.00");
        saleManifestEntity.setTotalAmount(SteelardHelp.formatMoney(allTotalPrice));
        saleManifestEntity.setPayableAmount(SteelardHelp.formatMoney(allTotalPrice));
        LinkBus.sendBroadcast(new OnSaleManifestSyncEvent(saleManifestEntity));

        cur_allTotalPrice = allTotalPrice;
        upTprice1();
    }


    private void upTprice1() {
        subtotalView.upSubtotalTotalPrice(SteelardHelp.formatMoney(cur_allTotalPrice == 0 ? (cur_allTotalPrice + cur_weightTotalPrice) : cur_allTotalPrice));
    }

    @Override
    public boolean hasGoodEntity(long itemId) {

        if (souceList != null) {
            List<OrderEntity.GoodEntity> gs = new ArrayList<>(souceList);
            for (OrderEntity.GoodEntity ge : gs) {
                if (itemId == ge.itemId) {
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    public void inEditSubtotal() {
        isEditSubtotal = true;
        subtotalView.editSubtotal(true);
    }

    @Override
    public void exitEditSubtotal() {
        isEditSubtotal = false;

        subtotalView.editSubtotal(false);
    }


    private void reOnWeightInfoChangeEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnWeightInfoChangeEvent>() {
            @Override
            public Class<OnWeightInfoChangeEvent> getBusEventClass() {
                return OnWeightInfoChangeEvent.class;
            }

            public void postonReceiver(OnWeightInfoChangeEvent data) {
                if (isExit()) return;
                cur_weightTotalPrice = data.getWeightChangeInfo().getTotalPrice();
                upTprice1();
            }

            @Override
            public void onReceiver(OnWeightInfoChangeEvent data) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        postonReceiver(data);
                    }
                });
            }
        }, cycleHelp, CycleHelp.CycleType.Destroy);
    }


    private void reOnSubtotalEvent() {
        LinkBusCycleWrapper.register(new Observer<OnSubtotalEvent>() {
            @Override
            public Class<OnSubtotalEvent> getBusEventClass() {
                return OnSubtotalEvent.class;
            }

            @Override
            public void onReceiver(OnSubtotalEvent data, Runnable nextRun) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        postonReceiver(data);
                        nextRun.run();
                    }
                });
            }


            private void postonReceiver(OnSubtotalEvent data) {
                String steelyardMac = data.getSteelyardMac();

                if (mSteelyardDataModule == null)
                    mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);


                if (data.isHandleSale()) {
                    if (mSteelyardDataModule != null) {
                        while (mSteelyardDataModule.removeGoodEntities(steelyardMac, 0) == 1) {
                        }
                    }

                    return;
                }
                data.setHandleSale(true);

                int oldSize = CollectionHelp.getSize(souceList);
                //P.d("Bill->postonReceiver->souceList.clear()前:" + oldSize);
                souceList.clear();
                //P.d("Bill->postonReceiver->souceList.clear()中:" + oldSize + ",isSyncForDevice:" + data.isSyncForDevice() + ",mSteelyardDataModule:" + (mSteelyardDataModule != null));

                List<OrderEntity.GoodEntity> goodEntities = null;

                if (data.isSyncForDevice()) {


                    souceList.clear();
                    goodEntities = mSteelyardDataModule == null ? null : mSteelyardDataModule.getGoodEntities(steelyardMac);//这里出了问题呀

                } else if (mSteelyardDataModule != null) {
                    goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);


                    if (goodEntities != null) {
                        for (int i = 0; i < goodEntities.size(); i++) {
//                                        if (goodEntities.get(i).weight <= 0 || goodEntities.get(i).unitType == 2) {

                            if (goodEntities.get(i).weight <= 0) {
                                mSteelyardDataModule.removeGoodEntities(steelyardMac, i);

                                goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);
                                i = 0;
                            }
                        }
                    }


                    int newSize = CollectionHelp.getSize(goodEntities);


                    if (newSize > oldSize) {
                        OrderEntity.GoodEntity[] readGoodEntities = goodEntities == null ? new OrderEntity.GoodEntity[0] : goodEntities.toArray(new OrderEntity.GoodEntity[goodEntities.size()]);
                        LinkBus.sendBroadcast(new OnSubtotalRealEvent(readGoodEntities, new OrderEntity.GoodEntity[]{data.getGoodEntitie()}, true));
                    }

                }
                //P.d("Bill->upSubtotal->goodEntities：" + goodEntities.size());
                try {
                    souceList.addAll(goodEntities);
                } catch (Exception e) {
                }
                upSubtotal();


                if (isSubtotalGopay) {
                    isSubtotalGopay = false;

                    mainHandler.postDelayed(onGoodImageTackrun = new Runnable() {
                        @Override
                        public void run() {

                            if (onGoodImageTackrun != null) {
                                onGoodImageTackrun = null;

                                tryGoPay();
                            }
                        }
                    }, AppConfig.isOrderImgTack() ? 3500 : 0);


                    if (goodImagePresenter != null)
                        goodImagePresenter.setOnTackGoodImage(new RunnablePR<String, Void>() {
                            @Override
                            public Void run(String s) {
                                Runnable run = onGoodImageTackrun;
                                if (run != null)
                                    run.run();
                                return null;
                            }
                        });

                }
                //P.d("Bill->postonReceiver->souceList.clear()后:" + souceList.size());
            }//
        }, cycleHelp, CycleHelp.CycleType.Destroy);
    }


    @Override
    public void onSteelyardKeyEvent(OnSteelyardKeyEvent data) {
        if (data.isIntercepted()) return;


        if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_PAY) {
            data.setIntercepted(true);
            if (FjApp.install.isFjing()) {
                RouterUINavigation.getInstance().showPayFjOrder(BaseFragmentActivity.getLastActivity());
            } else {

                tryQuickPay();
            }

        } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_DelegatePay) {//27
            data.setIntercepted(true);
            //P.p("Bill-> SubtotalPresenter ->onSteelyardKeyEvent->tryFullPay->getKeyCode：" + data.getKeyCode()+",从这里切入KEYCODE_DelegatePay，“扫码支付”");
            tryFullPay(DelegatePayTask.PayType_StaticDelegate);

        } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_VipW) {//25
            data.setIntercepted(true);
            //P.p("Bill-> SubtotalPresenter ->onSteelyardKeyEvent->tryFullPay->getKeyCode：" + data.getKeyCode()+",这里不知道从哪里触发的”");
            tryFullPay(DelegatePayTask.PayType_WVip);

        } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FJ) {
            data.setIntercepted(true);

            if (FjApp.install.isEnable()) {
                RouterUINavigation.getInstance().showFjOrder(BaseFragmentActivity.getLastActivity(), false);
            }
        } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_Fjswitch) {
            data.setIntercepted(true);
            if (!FjApp.install.isEnable()) return;


            RouterUINavigation.getInstance().showFjOrder(BaseFragmentActivity.getLastActivity(), FjApp.install.isFjing());
        } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_VipCard) {//26
            data.setIntercepted(true);
            //P.p("Bill-> SubtotalPresenter ->onSteelyardKeyEvent->tryFullPay->getKeyCode：" + data.getKeyCode()+",从这里切入KEYCODE_VipW，“会员支付”");
            tryFullPay(DelegatePayTask.PayType_WVip);
        } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {

            if (isEditSubtotal) {
                exitEditSubtotal();
                data.setIntercepted(true);
            }
        } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_CLEAR) {
            data.setIntercepted(true);

            subtotalView.confirmClearList(new Runnable() {
                @Override
                public void run() {
                    clearAll();


//                    VipModule vipModule = AppConst.getModuleManager().peekModule(VipModule.class);


                }
            });
        }
    }


    @Override
    public void onKeyNumberEvent(OnKeyNumberEvent data) {
        if (data.isIntercepted()) return;
        if (!isEditSubtotal) return;
        data.setIntercepted(true);
        try {

            if (mSteelyardDataModule == null)
                mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);

            String                       steelyardMac = RunTimeData.steelyardInfo.getSteelyardMac();
            List<OrderEntity.GoodEntity> goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);
            if (CollectionHelp.isEmpty(goodEntities)) return;

            int index = ((int) data.getNumber()) - 1;

            OrderEntity.GoodEntity deleteGoodEntity = goodEntities.get(index);
            if (goodEntities.size() < 10) {
                if (!data.isFinally()) {
                    mSteelyardDataModule.removeGoodEntities(steelyardMac, index);
                }
            } else {
                if (data.isFinally()) {
                    mSteelyardDataModule.removeGoodEntities(steelyardMac, index);
                }
            }


            goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);


            OrderEntity.GoodEntity[] readGoodEntities = goodEntities == null ? new OrderEntity.GoodEntity[0] : goodEntities.toArray(new OrderEntity.GoodEntity[goodEntities.size()]);
            LinkBus.sendBroadcast(new OnSubtotalRealEvent(readGoodEntities, new OrderEntity.GoodEntity[]{deleteGoodEntity}, false));


            upsouceList(steelyardMac);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void clearAll() {
        if (mSteelyardDataModule == null)
            mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);

        String steelyardMac = RunTimeData.steelyardInfo.getSteelyardMac();
        if (mSteelyardDataModule != null) {

            List<OrderEntity.GoodEntity> goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);
            if (!CollectionHelp.isEmpty(goodEntities))
                while (mSteelyardDataModule.removeGoodEntities(steelyardMac, 0) != 0) {
                }

            if (!CollectionHelp.isEmpty(goodEntities)) {
                OrderEntity.GoodEntity[] deletegoodEntities = goodEntities.toArray(new OrderEntity.GoodEntity[goodEntities.size()]);
                LinkBus.sendBroadcast(new OnSubtotalRealEvent(new OrderEntity.GoodEntity[0], deletegoodEntities, false));
            }
        }

        RunTimeData.steelyardInfo.removeState(SteelyardInfo.RunTimeState_subtotal);


        upsouceList(steelyardMac);

    }


    private void upsouceList(String steelyardMac) {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (isExit()) return;
                souceList.clear();
                try {
                    souceList.addAll(mSteelyardDataModule.getGoodEntities(steelyardMac));
                } catch (Exception e) {
                }
                //P.d("Bill->upSubtotal->03");
                upSubtotal();
            }
        });
    }


    private void tryGoPay() {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                isSubtotalGopay = false;
                if (mSteelyardDataModule == null)
                    mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);


                OrderEntity orderEntity = souceList.size() == 0 ? null : mSteelyardDataModule.onlyCreateOrderEntity(RunTimeData.steelyardInfo.getSteelyardMac(), null);


                if (orderEntity != null && StringHelp.isEmpty(orderEntity.orderNum))
                    orderEntity = null;


                if (orderEntity == null || CollectionHelp.isEmpty(orderEntity.getGoods())) {


                    OrderEntity.GoodEntity goodEntity = mSteelyardDataModule.getCurWeightChangeGood(RunTimeData.steelyardInfo.getSteelyardMac());//mSteelyardDataModule.regLastWeightChangeToOrderGood(RunTimeData.steelyardInfo.getSteelyardMac());


                    if (goodEntity != null && (goodEntity.unitPrice == 0 || goodEntity.weight == 0)) {
                        goodEntity = null;
                    }

                    if (goodEntity != null) {
                        isSubtotalGopay = true;

                        OrderEntity.GoodEntity goodEntity_ = mSteelyardDataModule.regLastWeightChangeToOrderGood(RunTimeData.steelyardInfo.getSteelyardMac());
                        goodEntity = goodEntity_;
                        LinkBus.sendBroadcast(new OnSubtotalEvent(RunTimeData.steelyardInfo.getSteelyardMac(), goodEntity));
                    } else {
                        subtotalView.showTips(3);
                    }

                } else {

                    RunTimeData.orderEntity = orderEntity;

                    if (FjApp.install.isFjing()) {


                        RouterUINavigation.getInstance().showPayFjOrder(BaseFragmentActivity.getLastActivity());
                    } else if (RunTimeData.isQuickPay) {

                        FunHelp.quickPay();
                    } else {
                        //P.p("Bill-> SubtotalPresenter ->onSteelyardKeyEvent->tryGoPay->应该从这里全支付。");
                        subtotalView.showPay();
                    }
                }
            }
        });


    }

    @Override
    public void tryQuickPay() {
        RunTimeData.isQuickPay = true;
        tryGoPay();
    }

    @Override
    public void tryFullPay(@DelegatePayTask.PayType int payType) {
        RunTimeData.tmpPayType = payType;
        RunTimeData.isQuickPay = false;
        tryGoPay();
    }
}